package com.witmore.neutron.ai.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.witmore.neutron.ai.db.entity.PermissionDO;
import com.witmore.neutron.ai.db.entity.RolePermissionDO;
import com.witmore.neutron.ai.db.entity.RoleUserDO;
import com.witmore.neutron.ai.db.mapper.PermissionMapper;
import com.witmore.neutron.ai.db.mapper.RolePermissionMapper;
import com.witmore.neutron.ai.db.mapper.RoleUserMapper;
import com.witmore.neutron.ai.web.apiv2.controller.vo.*;
import com.witmore.neutron.ai.web.service.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import java.util.stream.Collectors;

/**
 * 权限服务实现类
 * Author: 豆子高
 * Date: 2025/1/2
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<PermissionDO> getPermissionsByUserId(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }

        // 1. 查询用户的角色
        List<RoleUserDO> roleUserList = roleUserMapper.selectList(
                new LambdaQueryWrapper<RoleUserDO>()
                        .eq(RoleUserDO::getUserId, userId)
        );

        if (roleUserList.isEmpty()) {
            return new ArrayList<>();
        }

        // 2. 获取角色ID列表
        List<Long> roleIds = roleUserList.stream()
                .map(RoleUserDO::getRoleId)
                .collect(Collectors.toList());

        // 3. 查询角色对应的权限
        List<RolePermissionDO> rolePermissionList = rolePermissionMapper.selectList(
                new LambdaQueryWrapper<RolePermissionDO>()
                        .in(RolePermissionDO::getRoleId, roleIds)
        );

        if (rolePermissionList.isEmpty()) {
            return new ArrayList<>();
        }

        // 4. 获取权限ID列表（去重）
        List<Long> permissionIds = rolePermissionList.stream()
                .map(RolePermissionDO::getPermissionId)
                .distinct()
                .collect(Collectors.toList());

        // 5. 查询权限详细信息
        List<PermissionDO> permissionList = permissionMapper.selectList(
                new LambdaQueryWrapper<PermissionDO>()
                        .in(PermissionDO::getId, permissionIds)
                        .eq(PermissionDO::getStatus, 1) // 只查询启用状态的权限
                        .eq(PermissionDO::getIsDeleted, 0) // 只查询未删除的权限
        );

        return permissionList;
    }

    @Override
    public List<String> getPermissionNamesByUserId(Long userId) {
        List<PermissionDO> permissions = getPermissionsByUserId(userId);
        
        return permissions.stream()
                .map(PermissionDO::getCode)
                .collect(Collectors.toList());
    }

    @Override
    public Page<PermissionResult> getPermissionPage(PermissionQueryParam queryParam) {
        Page<PermissionDO> page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());
        
        LambdaQueryWrapper<PermissionDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PermissionDO::getIsDeleted, 0);
        
        // 条件查询
        if (StringUtils.isNotBlank(queryParam.getName())) {
            wrapper.like(PermissionDO::getName, queryParam.getName());
        }
        if (StringUtils.isNotBlank(queryParam.getCode())) {
            wrapper.like(PermissionDO::getCode, queryParam.getCode());
        }
        if (queryParam.getType() != null) {
            wrapper.eq(PermissionDO::getType, queryParam.getType());
        }
        if (queryParam.getParentId() != null) {
            wrapper.eq(PermissionDO::getParentId, queryParam.getParentId());
        }
        if (queryParam.getStatus() != null) {
            wrapper.eq(PermissionDO::getStatus, queryParam.getStatus());
        }
        
        wrapper.orderByAsc(PermissionDO::getSort).orderByAsc(PermissionDO::getId);
        
        Page<PermissionDO> permissionPage = permissionMapper.selectPage(page, wrapper);
        
        // 转换为结果对象
        Page<PermissionResult> resultPage = new Page<>();
        BeanUtils.copyProperties(permissionPage, resultPage);
        
        List<PermissionResult> resultList = permissionPage.getRecords().stream()
                .map(this::convertToResult)
                .collect(Collectors.toList());
        
        resultPage.setRecords(resultList);
        return resultPage;
    }

    @Override
    public List<PermissionResult> getPermissionTree() {
        // 查询所有启用的权限
        List<PermissionDO> allPermissions = permissionMapper.selectList(
                new LambdaQueryWrapper<PermissionDO>()
                        .eq(PermissionDO::getIsDeleted, 0)
                        .orderByAsc(PermissionDO::getSort)
                        .orderByAsc(PermissionDO::getId)
        );
        
        // 转换为结果对象
        List<PermissionResult> permissionResults = allPermissions.stream()
                .map(this::convertToResult)
                .collect(Collectors.toList());
        
        // 构建树形结构
        return buildTree(permissionResults, 0L);
    }

    @Override
    public PermissionResult getPermissionById(Long id) {
        PermissionDO permission = permissionMapper.selectById(id);
        if (permission == null || permission.getIsDeleted() == 1) {
            return null;
        }
        return convertToResult(permission);
    }

    @Override
    public boolean createPermission(PermissionCreateParam createParam, String creator) {
        // 检查权限编码是否已存在
        if (checkPermissionCodeExists(createParam.getCode(), null)) {
            throw new RuntimeException("权限编码已存在");
        }
        
        PermissionDO permission = new PermissionDO();
        BeanUtils.copyProperties(createParam, permission);
        permission.setCreator(creator);
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        permission.setIsDeleted((byte) 0);
        
        return permissionMapper.insert(permission) > 0;
    }

    @Override
    public boolean updatePermission(PermissionUpdateParam updateParam) {
        PermissionDO existingPermission = permissionMapper.selectById(updateParam.getId());
        if (existingPermission == null || existingPermission.getIsDeleted() == 1) {
            throw new RuntimeException("权限不存在");
        }
        
        // 检查权限编码是否已存在（排除当前记录）
        if (StringUtils.isNotBlank(updateParam.getCode()) && 
            checkPermissionCodeExists(updateParam.getCode(), updateParam.getId())) {
            throw new RuntimeException("权限编码已存在");
        }
        
        PermissionDO permission = new PermissionDO();
        BeanUtils.copyProperties(updateParam, permission);
        permission.setUpdateTime(LocalDateTime.now());
        
        return permissionMapper.updateById(permission) > 0;
    }

    @Override
    public boolean deletePermission(Long id) {
        PermissionDO permission = permissionMapper.selectById(id);
        if (permission == null || permission.getIsDeleted() == 1) {
            return false;
        }
        
        // 检查是否有子权限
        long childCount = permissionMapper.selectCount(
                new LambdaQueryWrapper<PermissionDO>()
                        .eq(PermissionDO::getParentId, id)
                        .eq(PermissionDO::getIsDeleted, 0)
        );
        
        if (childCount > 0) {
            throw new RuntimeException("存在子权限，无法删除");
        }
        
        // 逻辑删除
        permission.setIsDeleted((byte) 1);
        permission.setUpdateTime(LocalDateTime.now());
        
        return permissionMapper.updateById(permission) > 0;
    }

    @Override
    public boolean batchDeletePermission(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        
        for (Long id : ids) {
            if (!deletePermission(id)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean checkPermissionCodeExists(String code, Long excludeId) {
        if (StringUtils.isBlank(code)) {
            return false;
        }
        
        LambdaQueryWrapper<PermissionDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PermissionDO::getCode, code)
               .eq(PermissionDO::getIsDeleted, 0);
        
        if (excludeId != null) {
            wrapper.ne(PermissionDO::getId, excludeId);
        }
        
        return permissionMapper.selectCount(wrapper) > 0;
    }

    /**
     * 转换为结果对象
     */
    private PermissionResult convertToResult(PermissionDO permission) {
        PermissionResult result = new PermissionResult();
        BeanUtils.copyProperties(permission, result);
        return result;
    }

    /**
     * 构建树形结构
     */
    private List<PermissionResult> buildTree(List<PermissionResult> allPermissions, Long parentId) {
        List<PermissionResult> tree = new ArrayList<>();
        
        for (PermissionResult permission : allPermissions) {
            if (parentId.equals(permission.getParentId())) {
                List<PermissionResult> children = buildTree(allPermissions, permission.getId());
                permission.setChildren(children);
                tree.add(permission);
            }
        }
        
        return tree;
    }
}